//
//  QuickCardProcess.m
//  QRMaster
//
//  Created by myApple on 16/5/26.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "QuickCardProcess.h"
#import "OpertionPlist.h"
#import "RequestNetWork.h"
#import "QuickCardLogic.h"
#import "AFNetworking.h"
#import "InternationalControl.h"

@interface QuickCardProcess()
{
    NSUserDefaults * userInfo;
    QuickCardLogic * quickLogic;
}

@end

@implementation QuickCardProcess

-(instancetype)init
{
    self = [super init];
    if (self) {
        userInfo = [NSUserDefaults standardUserDefaults];
        quickLogic = [[QuickCardLogic alloc]init];
    }
    return self;
}

#pragma mark - initNoRoomData
-(QuickCardModel *)prepareNoRoomData:(NSInteger)index;
{
    QuickCardModel * model = [[QuickCardModel alloc]init];
    model.communityId = @"";
    model.communityName = @"";
    model.buildingName = @"";
    model.floorName = @"";
    model.roomId = @"";
    model.roomName = @"";
    model.collectId = @"";
    model.index = index;
    return model;
}

#pragma mark - 从缓存中读取收藏房卡
-(void)getCollectCardByPlist
{
    __weak QuickCardProcess * weakSelf = self;
    [quickLogic queryAllQuickCardBlock:^(NSMutableArray *quickCardArray) {
        NSMutableArray * collectionArray = [weakSelf sortArray:quickCardArray];
        if ([weakSelf collectCardBlcok]) {
            weakSelf.collectCardBlcok(collectionArray);
        }
    }];
}

#pragma mark - 从数据库中读取缓存
-(void)getCollectFromDBBlock:(void (^)(NSArray *))resultBlock
{
    __weak QuickCardProcess * weakSelf = self;
    [quickLogic queryAllQuickCardBlock:^(NSMutableArray *quickCardArray) {
        NSMutableArray * collectionArray = [weakSelf sortArray:quickCardArray];
        resultBlock(collectionArray);
    }];
}

#pragma mark - 添加网络收藏房卡
-(void)addCollectionCard:(NSMutableDictionary *)dict file:(NSData *)imageData block:(void (^)(NSString *, NSString *))resultBlock
{
    NSString *  currentLanagage = [InternationalControl userLanguage];
    if ([currentLanagage isEqualToString:@"zh-Hans-CN"]) {
        currentLanagage = @"zh_cn";
    }
    else if([currentLanagage isEqualToString:@"zh-Hant-HK"])
    {
        currentLanagage = @"zh_tw";
    }
    else if([currentLanagage isEqualToString:@"zh-Hant-TW"])
    {
        currentLanagage = @"zh_tw";
    }
    else if([currentLanagage isEqualToString:@"en"])
    {
        currentLanagage = @"en_us";
    }
    [dict setValue:currentLanagage forKey:@"l"];
    AFHTTPRequestOperationManager *mgr=[AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    [mgr POST:POST(ADDCOLLECTROOM) parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (imageData != nil) {
            [formData appendPartWithFileData:imageData name:@"file" fileName:@"photo.jpg" mimeType:@"image/jpg"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSDictionary * downLoadDict = [obj objectForKey:@"data"];
        QuickCardModel * model = [[QuickCardModel alloc]init];
        model.communityId = [downLoadDict objectForKey:@"communityId"];
        model.communityName = [downLoadDict objectForKey:@"communityName"];
        model.buildingName = [downLoadDict objectForKey:@"buildName"];
        model.buildingId = [downLoadDict objectForKey:@"buildId"];
        model.floorName = [downLoadDict objectForKey:@"floorName"];
        model.floorId = [downLoadDict objectForKey:@"floorId"];
        model.roomId = [downLoadDict objectForKey:@"roomId"];
        model.roomName = [downLoadDict objectForKey:@"roomName"];
        model.collectId = [downLoadDict objectForKey:@"collectId"];
        model.index = [[downLoadDict objectForKey:@"index"]integerValue];
        model.customerName = [downLoadDict objectForKey:@"name"];
        model.imageURL = [downLoadDict objectForKey:@"imageUrl"];
        [quickLogic deleteQuickCard:model.communityId roomId:model.roomId];
        [quickLogic insertQuickCard:model];
            resultBlock([obj objectForKey:@"info"],nil);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if ([error.userInfo objectForKey:ERRORINFO]) {
            id obj = [NSJSONSerialization JSONObjectWithData:[error.userInfo objectForKey:ERRORINFO] options:NSJSONReadingMutableContainers error:nil];
            resultBlock(nil,[obj objectForKey:@"info"]);
        }
    }];

}

#pragma mark - 取消收藏房卡
-(void)cancelCollectionCard:(NSMutableDictionary *)dict block:(void (^)(NSString *, NSString *))resultBlock
{
    NSString *  currentLanagage = [InternationalControl userLanguage];
    if ([currentLanagage isEqualToString:@"zh-Hans-CN"]) {
        currentLanagage = @"zh_cn";
    }
    else if([currentLanagage isEqualToString:@"zh-Hant-HK"])
    {
        currentLanagage = @"zh_tw";
    }
    else if([currentLanagage isEqualToString:@"zh-Hant-TW"])
    {
        currentLanagage = @"zh_tw";
    }
    else if([currentLanagage isEqualToString:@"en"])
    {
        currentLanagage = @"en_us";
    }
    NSMutableDictionary * cancelDict = [[NSMutableDictionary alloc]init];
    [cancelDict setValue:currentLanagage forKey:@"l"];
    [cancelDict setValue:[dict objectForKey:@"roomId"] forKey:@"roomId"];
    [cancelDict setValue:UID forKey:@"id"];
    [cancelDict setValue:TOKEN forKey:@"token"];
    [cancelDict setValue:[dict objectForKey:@"communityId"] forKey:@"communityId"];
    RequestNetWork * rn = [RequestNetWork sharedRequestNetWork];
    [rn initWithPath:POST(DELETECOLLECTROOM) params:cancelDict block:^(id downLoadData, id error) {
        if (downLoadData) {
            [quickLogic deleteQuickCard:[dict objectForKey:@"communityId"] roomId:[dict objectForKey:@"roomId"]];
             resultBlock([downLoadData objectForKey:@"info"],nil);
        }
        else
        {
            resultBlock(nil,[error objectForKey:@"info"]);
        }
    }];
}

#pragma mark - 修改网络收藏房卡
-(void)eidtCollectionCard:(NSMutableDictionary *)dict file:(NSData *)imageData block:(void (^)(NSString *, NSString *))resultBlock
{
    NSString *  currentLanagage = [InternationalControl userLanguage];
    if ([currentLanagage isEqualToString:@"zh-Hans-CN"]) {
        currentLanagage = @"zh_cn";
    }
    else if([currentLanagage isEqualToString:@"zh-Hant-HK"])
    {
        currentLanagage = @"zh_tw";
    }
    else if([currentLanagage isEqualToString:@"zh-Hant-TW"])
    {
        currentLanagage = @"zh_tw";
    }
    else if([currentLanagage isEqualToString:@"en"])
    {
        currentLanagage = @"en_us";
    }
    [dict setValue:currentLanagage forKey:@"l"];
    AFHTTPRequestOperationManager *mgr=[AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    [mgr POST:POST(EDITCOLLECTIONROOM) parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (imageData != nil) {
            [formData appendPartWithFileData:imageData name:@"file" fileName:@"photo.jpg" mimeType:@"image/jpg"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        id obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSDictionary * downLoadDict = [obj objectForKey:@"data"];
        QuickCardModel * model = [[QuickCardModel alloc]init];
        model.communityId = [downLoadDict objectForKey:@"communityId"];
        model.communityName = [downLoadDict objectForKey:@"communityName"];
        model.buildingName = [downLoadDict objectForKey:@"buildName"];
        model.buildingId = [downLoadDict objectForKey:@"buildId"];
        model.floorName = [downLoadDict objectForKey:@"floorName"];
        model.floorId = [downLoadDict objectForKey:@"floorId"];
        model.roomId = [downLoadDict objectForKey:@"roomId"];
        model.roomName = [downLoadDict objectForKey:@"roomName"];
        model.collectId = [downLoadDict objectForKey:@"collectId"];
        model.index = [[downLoadDict objectForKey:@"index"]integerValue];
        model.customerName = [downLoadDict objectForKey:@"name"];
        model.imageURL = [downLoadDict objectForKey:@"imageUrl"];
        [quickLogic deleteQuickCard:model.communityId roomId:model.roomId];
        [quickLogic insertQuickCard:model];
        resultBlock([obj objectForKey:@"info"],nil);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if ([error.userInfo objectForKey:ERRORINFO]) {
            id obj = [NSJSONSerialization JSONObjectWithData:[error.userInfo objectForKey:ERRORINFO] options:NSJSONReadingMutableContainers error:nil];
            resultBlock(nil,[obj objectForKey:@"info"]);
        }
    }];
}

#pragma mark - 获取网络收藏房卡信息
-(void)getFaveriterCard
{
   __block NSMutableArray * collectArray = [[NSMutableArray alloc]init];
    __weak QuickCardProcess * weakSelf = self;
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [rnk initWithPath:POST(GETCOLLECTROOM) params:postDict block:^(id downLoadData, id error) {
        if ([downLoadData objectForKey:@"data"] != nil) {
            NSArray * collectionCardArray = [downLoadData objectForKey:@"data"];
            for (NSDictionary * dict in collectionCardArray) {
                QuickCardModel * model = [[QuickCardModel alloc]init];
                model.communityId = [dict objectForKey:@"communityId"];
                model.communityName = [dict objectForKey:@"communityName"];
                model.buildingName = [dict objectForKey:@"buildName"];
                model.buildingId = [dict objectForKey:@"buildId"];
                model.floorName = [dict objectForKey:@"floorName"];
                model.floorId = [dict objectForKey:@"floorId"];
                model.roomId = [dict objectForKey:@"roomId"];
                model.roomName = [dict objectForKey:@"roomName"];
                model.collectId = [dict objectForKey:@"collectId"];
                model.index = [[dict objectForKey:@"index"]integerValue];
                model.customerName = [dict objectForKey:@"name"];
                model.imageURL = [dict objectForKey:@"imageUrl"];
                [collectArray addObject:model];
                [quickLogic deleteQuickCard:model.communityId roomId:model.roomId];
                [quickLogic insertQuickCard:model];
            }
        }
        else
        {
            
        }
        collectArray = [weakSelf sortArray:collectArray];
        if (weakSelf.collectCardBlcok) {
            weakSelf.collectCardBlcok(collectArray);
        }
    }];
    
}

-(void)modifyCollectCard:(NSInteger)index array:(NSMutableArray *)collectArray
{
    
}


#pragma mark - 置顶一个数据后的排序
-(void)sortArrayIn:(NSMutableArray *)array by:(QuickCardModel *)model
{
    //排序
    for (NSInteger i = 0 ; i < 5; i ++) {
        QuickCardModel * obj = array[i];
            if (model.index == obj.index) {
                [array removeObject:obj];
                 model.index = 1;
                [array insertObject:model atIndex:0];
            }
            else if (model.index > obj.index)
            {
                obj.index ++;
            }
    }
    //上传
    __block NSMutableArray * indexArray = [[NSMutableArray alloc]init];
    for (NSInteger i = 0 ; i < array.count; i ++) {
        QuickCardModel * newModel = array[i];
        if ([newModel.collectId isEqualToString:@""]) {
            [array removeObject:newModel];
        }
        else
        {
            NSMutableDictionary * dict = [[NSMutableDictionary alloc]init];
            [dict setValue:newModel.collectId forKey:@"collectId"];
            [dict setValue:[NSString stringWithFormat:@"%d",newModel.index] forKey:@"index"];
            [indexArray addObject:dict];
            [quickLogic deleteQuickCard:newModel.communityId roomId:newModel.roomId];
            [quickLogic insertQuickCard:newModel];
        }
    }
    
    //数组转化为json
    NSError * error = nil;
    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:indexArray options:NSJSONWritingPrettyPrinted error:&error];
    __block NSMutableArray * collectionArray = [[NSMutableArray alloc]init];
    __weak QuickCardProcess * weakSelf = self;
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:jsonData forKey:@"index"];
    [rnk initWithPath:POST(SORTCOLLECTIONROOM) params:postDict block:^(id downLoadData, id error) {
        if ([[downLoadData objectForKey:@"status"] integerValue] == 200) {
            collectionArray = [weakSelf sortArray:array];
            if (weakSelf.collectCardBlcok) {
                weakSelf.collectCardBlcok(collectionArray);
            }
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        
    }];
}


#pragma mark - 房卡排序
-(NSMutableArray *)sortArray:(NSMutableArray *)array
{
    NSMutableArray * sortArray = [NSMutableArray arrayWithArray:[array sortedArrayUsingComparator:^NSComparisonResult(QuickCardModel * model1, QuickCardModel * model2) {
        return [[NSNumber numberWithInt:model1.index] compare:[NSNumber numberWithInt:model2.index]];
    }]];
    //补上空房
    NSInteger count = sortArray.count;
    if (count >= 5) {
        return sortArray;
    }
    else if(count == 0)
    {
        for (NSInteger i = 0 ; i < 5; i ++) {
            [sortArray addObject:[self prepareNoRoomData:i + 1]];
        }
    }
    else
    {
        NSInteger preIndex = 1;
        for (NSInteger i = 0 ; i < count; i ++) {
            QuickCardModel * model = sortArray[i];
            if (model.index > preIndex) {
                [sortArray insertObject:[self prepareNoRoomData:preIndex] atIndex:i];
                i--;
            }
            else if(model.index == preIndex)
            {
                preIndex = model.index + 1;
            }
        }
        while (sortArray.count < 5) {
            [sortArray insertObject:[self prepareNoRoomData:sortArray.count + 1] atIndex:sortArray.count];
        }
    }
    return sortArray;
}

@end
